package com.bjsxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjsxt.domain.User;
import com.bjsxt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjsxt.domain.UserBank;
import com.bjsxt.mapper.UserBankMapper;
import com.bjsxt.service.UserBankService;

/**
 * @Description:  ${description}
 * @ClassName:      UserBankServiceImpl
 * @Author:  chenyu
 * @Date:    2025/3/11 11:21
 */
 
@Service
public class UserBankServiceImpl extends ServiceImpl<UserBankMapper, UserBank> implements UserBankService{

    @Autowired
    private UserService userService;
    /**
     * 查询用户的银行卡信息
     *
     * @param page  分页参数
     * @param usrId 用户的Id
     * @return
     */
    @Override
    public Page<UserBank> findByPage(Page<UserBank> page, Long usrId) {
        return page(page ,new LambdaQueryWrapper<UserBank>().eq(usrId != null ,UserBank::getUserId ,usrId));
    }

    /**
     * 通过用户的ID 查询用户的银行卡
     *
     * @param userId
     * @return
     */
    @Override
    public UserBank getUserBankByUserId(Long userId) {
        UserBank userBank = getOne(
                new LambdaQueryWrapper<UserBank>()
                        .eq(UserBank::getUserId, userId)
                        .eq(UserBank::getStatus, 1));
        return userBank;
    }

    @Override
    public boolean bindBank(Long userId, UserBank userBank) {
        String payPassword = userBank.getPayPassword();
        User user = userService.getById(userId);
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        if (!bCryptPasswordEncoder.matches(payPassword, user.getPaypassword())) {
            throw new IllegalArgumentException("用户支付密码错误");
        }
        Long id = userBank.getId();//id代表是否是修改操作
        if (id != null) {
            UserBank userBankObj = getById(id);
            if (userBankObj == null)
                throw new IllegalArgumentException("用户银行卡ID输入错误");
            return updateById(userBank);
        }
        //id为null，新增
        userBank.setUserId(userId);
        return save(userBank);
    }
}
